<template>
  <div class="reservation-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>预约管理</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="自习室">
          <el-select 
            v-model="searchForm.roomId" 
            placeholder="请选择自习室" 
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="room in studyRooms"
              :key="room.id"
              :label="room.name"
              :value="room.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss" 
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59)
            ]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 预约列表 -->
      <div class="table-container">
        <el-table 
          :data="reservations.records" 
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column prop="username" label="用户" width="120" />
          <el-table-column prop="roomName" label="自习室" width="150" />
          <el-table-column prop="seatNumber" label="座位号" width="100" />
          <el-table-column prop="startTime" label="开始时间" width="180">
            <template #default="scope">
              {{ scope.row.startTime ? formatDate(scope.row.startTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="180">
            <template #default="scope">
              {{ scope.row.endTime ? formatDate(scope.row.endTime) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button 
                v-if="scope.row.status === 1 || scope.row.status === 2" 
                type="success" 
                size="small" 
                @click="handleEndReservation(scope.row)"
              >
                结束预约
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="reservations.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/dateUtil'
import dayjs from 'dayjs'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const studyRooms = ref([])
const reservations = ref({ records: [], total: 0 })

const searchForm = reactive({
  roomId: null,
  dateRange: []
})

// 获取自习室列表
const loadStudyRooms = async () => {
  try {
    const res = await request.get('/admin/study-rooms/list')
    if (res.code === 200) {
      studyRooms.value = res.data
    }
  } catch (error) {
    console.error('Failed to load study rooms:', error)
  }
}

// 加载预约列表
const loadReservations = async () => {
  try {
    loading.value = true
    let params = {
      current: currentPage.value,
      size: pageSize.value
    }

    if (searchForm.roomId) {
      params.roomId = searchForm.roomId
    }
    
    if (searchForm.dateRange?.length === 2) {
      params.startTime = dayjs(searchForm.dateRange[0]).format('YYYY-MM-DD HH:mm:ss')
      params.endTime = dayjs(searchForm.dateRange[1]).format('YYYY-MM-DD HH:mm:ss')
    }

    console.log('发送查询参数:', params)
    const res = await request.post('/admin/reservations/search', params)

    if (res.code === 200) {
      reservations.value = res.data
    } else {
      ElMessage.error(res.message || '加载预约列表失败')
    }
  } catch (error) {
    console.error('完整错误信息:', error)
    ElMessage.error(error.response?.data?.message || error.message || '加载预约列表失败')
  } finally {
    loading.value = false
  }
}

// 结束预约
const handleEndReservation = async (row) => {
  try {
    await ElMessageBox.confirm('确定要结束该预约吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await request.put(`/admin/reservations/${row.id}/end`)
    if (res.code === 200) {
      ElMessage.success('预约已结束')
      loadReservations()
    } else {
      ElMessage.error(res.message || '结束预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to end reservation:', error)
      ElMessage.error('结束预约失败')
    }
  }
}

// 重置搜索条件
const resetSearch = () => {
  try {
    searchForm.roomId = null
    searchForm.dateRange = []
    currentPage.value = 1
    pageSize.value = 10
    loadReservations()
  } catch (error) {
    console.error('重置错误:', error)
    ElMessage.error('重置失败')
  }
}

// 搜索处理函数
const handleSearch = () => {
  try {
    if (searchForm.dateRange?.length === 2) {
      const startTime = new Date(searchForm.dateRange[0])
      const endTime = new Date(searchForm.dateRange[1])
      
      if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
        ElMessage.warning('请选择有效的日期范围')
        return
      }
      
      if (startTime > endTime) {
        ElMessage.warning('开始时间不能晚于结束时间')
        return
      }
    }
    
    currentPage.value = 1
    loadReservations()
  } catch (error) {
    console.error('搜索错误:', error)
    ElMessage.error('搜索出错，请检查输入')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadReservations()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadReservations()
}

const formatDate = (date) => {
  if (!date) return '-'
  try {
    return formatDateTime(date)
  } catch (error) {
    console.error('Date formatting error:', error)
    return date // 如果格式化失败，返回原始值
  }
}

const getStatusType = (status) => {
  const types = {
    0: 'info',    // 已取消
    1: 'success', // 生效中
    2: 'warning', // 使用中
    3: 'info'     // 已完成
  }
  return types[status]
}

const getStatusText = (status) => {
  const texts = {
    0: '已取消',
    1: '生效中',
    2: '使用中',
    3: '已完成'
  }
  return texts[status]
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该预约吗？此操作不可恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await request.delete(`/admin/reservations/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('预约删除成功')
      loadReservations()
    } else {
      // 处理后端返回的错误信息
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除预约失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

onMounted(() => {
  loadStudyRooms()
  loadReservations()
})
</script>

<style scoped>
.box-card {
  width: 100%;
}

.search-form {
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
}

.table-container :deep(.el-table) {
  width: 100% !important;
}

.table-container :deep(.el-table__header),
.table-container :deep(.el-table__body) {
  width: 100% !important;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 